package net.lulihu.common_util.jdbc.config;

import net.lulihu.common_util.jdbc.MultipleDataSourceManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * 默认jdbc配置
 * <p>
 * 使用spring data jdbc作为事务数据源管理者
 */
@Configuration
@ConditionalOnClass({DataSource.class, JdbcTemplate.class})
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class DefaultJdbcConfiguration {

    @Bean
    public JdbcTemplate jdbcTemplate(@Autowired DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 将spring的数据源传递到工具管理方法中方便使用
     */
    @Bean
    public MultipleDataSourceManage multipleDataSourceManage(@Autowired JdbcTemplate jdbcTemplate) {
        DataSource dataSource = jdbcTemplate.getDataSource();

        MultipleDataSourceManage dataSourceManage = MultipleDataSourceManage.getInstance();
        String defaultDataSource = "defaultDataSource";
        dataSourceManage.addDataSource(defaultDataSource, dataSource);
        dataSourceManage.setDefaultDataSource(defaultDataSource);
        return dataSourceManage;
    }

}
